import time
import pytesseract
from PIL import Image, ImageEnhance
from selenium import webdriver
from selenium.webdriver.common.by import By

url = "http://wgpc.wzsafety.gov.cn/login_qygl.htm"
# 1、打开浏览器，最大化浏览器
driver = webdriver.Firefox()
driver.get(url)
driver.implicitly_wait(1)
driver.maximize_window()

# 用户名元素
userElement = driver.find_element(By.XPATH, "/html/body/div/div[2]/ul/li[1]/input")
#userElement = driver.find_element_by_id("uid_51")
# 密码元素
passElement = driver.find_element(By.XPATH, "/html/body/div/div[2]/ul/li[2]/input")
#passElement = driver.find_element_by_id("password_51")
# 验证码输入框元素
codeElement = driver.find_element(By.XPATH, "/html/body/div/div[2]/ul/li[3]/input")
#codeElement = driver.find_element_by_id("validataimage_50")
# 验证图片元素
imgElement = driver.find_element(By.XPATH, "/html/body/div/div[2]/ul/li[3]/img")
#imgElement = driver.find_elements_by_class_name("ValidataImage")
# 2、截取屏幕内容，保存到本地
driver.save_screenshot("E://01.png")

# 3、打开截图，获取验证码位置，截取保存验证码
ran = Image.open("E://01.png")
box = (1120, 280, 1180, 310)  # 获取验证码位置,自动定位不是很明白，就使用了手动定位，代表（左，上，右，下）
ran.crop(box).save("E://02.png")

# 4、获取验证码图片，读取验证码
imageCode = Image.open("E://02.png")  # 图像增强，二值化
# imageCode.load()
sharp_img = ImageEnhance.Contrast(imageCode).enhance(2.0)
sharp_img.save("E://03.png")
sharp_img.load()  # 对比度增强
time.sleep(2)
print(sharp_img)
code = pytesseract.image_to_string(sharp_img).strip()
# 5、收到验证码，进行输入验证
print(code)

userElement.send_keys('91330324554002884Q')
passElement.send_keys('91330324554002884Q')

# time.sleep(3)
codeElement.send_keys(code)
#click_login = driver.find_element(By.XPATH, "/html/body/form/table/tbody/tr/td[2]/table/tbody/tr[6]/td[2]/input")
click_login = driver.find_element_by_id("b_denglu_51")
click_login.click()